<template>
  <el-dialog :model-value="editDialogVisible" @opened="handleDialogOpened" :title="'编辑商品'" width="700px" destroy-on-close
    :close-on-click-modal="false" :before-close="handleCancel">
    <el-form v-loading="loading" ref="editGoodsFormRef" :model="editGoodsForm" status-icon :rules="editGoodsFormRules"
      label-width="120px" class="edit-merchant">
      <el-form-item prop="name" label="商品名称">
        <el-input v-model.trim="editGoodsForm.name" show-word-limit maxlength="100"></el-input>
      </el-form-item>

      <el-form-item prop="productImg" label="商品图片">
        <upload :limit="1" v-model="editGoodsForm.thumbnailUrl" list-type="picture-card">
          <el-icon>
            <Plus />
          </el-icon>
        </upload>
      </el-form-item>

      <el-form-item prop="mallProductCategory" label="商品分类">
        <el-select v-model="editGoodsForm.categoryId">
          <el-option v-for="(item, index) in goodsCateList" :key="index" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item class="long-character-label" label="商品价格" prop="combinedProductPrice">
        <div class="vertical-form-content">
          <div class="line-input">
            <el-form-item prop="showMinCurrencyPrice">
              <el-input v-model="editGoodsForm.showMinCurrencyPrice">
                <template #append> 积分 </template>
              </el-input>
            </el-form-item>
            <div style="width: 5px; height: 100%"></div>
            <el-form-item prop="showMinPrice">
              <el-input v-model="editGoodsForm.showMinPrice">
                <template #append> 元 </template>
              </el-input>
            </el-form-item>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="productLimit" label="兑换限制（件/人）">
        <el-input type="number" v-model="editGoodsForm.productLimit"></el-input>
      </el-form-item>

      <el-form-item label="排序" prop="sort">

        <el-input-number :step="1" step-strictly v-model="editGoodsForm.sort" min="1" max="99999999"></el-input-number>
      </el-form-item>

      <el-form-item prop="description" label="使用说明">
        <el-input type="textarea" autosize v-model="editGoodsForm.description"></el-input>
      </el-form-item>

      <el-form-item prop="detailImg" label="商品图文介绍">
        <div class="text-box" v-if="!flag" v-html="formatStr(editGoodsForm.detailText)">
        </div>
        <rich-editor v-if="flag" :initial-value="richEditorInitialValue" @change="handleDetailTextChange"></rich-editor>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { useGetGoodsCategory } from "@/views/pointsMall/compositions/useGetGoodsCategory";
import { editGoods, getGoodsDetail } from "@/api/pointsMall";
import { FormInstance, FormRules } from "element-plus";
import { IGoodsPageRow } from "@/api/modules/pointsMall";
import RichEditor from "@/components/RichEditor.vue";
import {
  positiveInteger,
  positiveInteger_0,
  positiveNumber_decimal$2,
} from "@/utils/commonRegexp";

const props = defineProps<{
  show: boolean;
  rowData: IGoodsPageRow;
}>();
const emits = defineEmits(["update:show", "saved"]);

const loading = ref(false);
const editDialogVisible = computed({
  get: () => {
    return props.show;
  },
  set: (value) => {
    emits("update:show", value);
  },
});
const { goodsCateList, getGoodsCate } = useGetGoodsCategory();
const richEditor = ref<InstanceType<typeof RichEditor> | null>(null);
const richEditorInitialValue = ref("");
const editGoodsFormRef = ref<FormInstance>();
//商品图文是否仅仅预览
const flag = ref(true)
const editGoodsForm = reactive({
  name: "",
  thumbnailUrl: "",
  categoryId: null,
  productLimit: 0,
  showMinPrice: 0,
  showMinCurrencyPrice: null,
  description: "",
  detailText: "",
  sort: 1,
});
const editGoodsFormRules = reactive<FormRules>({
  categoryId: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  name: [
    {
      required: true,
      message: "请输入商品名称",
      trigger: "blur",
    },
  ],

  combinedProductPrice: [
    {
      required: true,
      validator(rule, val, callback) {
        if (
          isEmpty(editGoodsForm.showMinCurrencyPrice) ||
          isEmpty(editGoodsForm.showMinPrice)
        ) {
          callback(new Error("商品价格是必填的"));
          editGoodsFormRef.value?.clearValidate([
            "showMinCurrencyPrice",
            "showMinPrice",
          ]);
        } else {
          callback();
        }
      },
    },
  ],
  showMinCurrencyPrice: [
    {
      required: true,
      trigger: "blur",
      validator(rule, val, callback) {
        if (!positiveInteger_0.test("" + editGoodsForm.showMinCurrencyPrice)) {
          callback(new Error("商品售价【积分】只能0或正整数"));
        } else if (Number(editGoodsForm.showMinCurrencyPrice) > 9999999999) {
          callback(new Error("超过上限【99,9999,9999】"));
        } else {
          editGoodsFormRef.value?.clearValidate([
            "showMinCurrencyPrice",
            "combinedProductPrice",
          ]);
          callback();
        }
      },
    },
  ],
  showMinPrice: [
    {
      required: true,
      trigger: "blur",
      validator(rule, val, callback) {
        if (!positiveNumber_decimal$2.test("" + editGoodsForm.showMinPrice)) {
          callback(new Error("商品售价【现金】需大于0且仅保留2位小数"));
        } else if (Number(editGoodsForm.showMinPrice) > 9999999999) {
          callback(new Error("超过上限【99,9999,9999】"));
        } else {
          editGoodsFormRef.value?.clearValidate([
            "showMinPrice",
            "combinedProductPrice",
          ]);
          callback();
        }
      },
    },
  ],
  thumbnailUrl: [
    {
      required: true,
      message: "请上传商品图片",
      trigger: "change",
    },
  ],
  stock: [
    {
      required: true,
      message: "请输入兑换库存",
      trigger: "blur",
    },
  ],
  productLimit: [
    {
      required: true,
      message: "请输入兑换限制",
      trigger: "blur",
    },
    {
      message: "兑换限制只能是正整数",
      validator(rule, val, callback) {
        if (!/^[1-9]*[1-9][0-9]*$/.test(val)) {
          callback(new Error("兑换限制只能是正整数"));
        } else {
          callback();
        }
      },
    },
    {
      message: "超过上限【9999,9999】",
      validator(rule, val, callback) {
        if (Number(val) > 99999999) {
          callback(new Error("超过上限【9999,9999】"));
        } else {
          callback();
        }
      },
    },
  ],
  showPrice: [
    {
      required: true,
      message: "请输入兑换价",
      trigger: "blur",
    },
  ],
  sort: [
    {
      required: true,
      message: "请输入排序",
      trigger: "change",
    },
  ],
});

const handleDetailTextChange = ({ innerHTML }: { innerHTML: string }) => {
  editGoodsForm.detailText = innerHTML;
};

const isEmpty = (val: any) => {
  return val === null || val === undefined || val === "";
};

const formatData = () => {
  const _editGoodsForm = { ...editGoodsForm };

  _editGoodsForm.productLimit = Number(_editGoodsForm.productLimit);
  _editGoodsForm.showMinPrice = parseInt((_editGoodsForm.showMinPrice * 100).toFixed(2).slice(0, -3));
  return _editGoodsForm;
};

const handleSave = async () => {
  editGoodsFormRef.value?.validate(async (validate, callback) => {
    if (validate) {
      const _editGoodsForm = formatData();
      loading.value = true;
      const rs = await editGoods(_editGoodsForm);
      loading.value = false;
      if (rs.code === 200) {
        ElMessage.success("保存成功");
        editDialogVisible.value = false;
        emits("saved", rs);
      }
    }
  });
};

const handleCancel = () => {
  editDialogVisible.value = false;
  richEditorInitialValue.value = ""; // quill 渲染完后修改绑定值会导致崩溃，置空触发vif, 下次打开后重新渲染
};

const _getGoodsDetail = async () => {
  loading.value = true;
  const rs = await getGoodsDetail({ id: props.rowData.id });

  loading.value = false;
  if (rs.code === 200) {
    rs.payload &&
      Object.keys(rs.payload).forEach((key) => {
        editGoodsForm[key] = rs.payload?.[key] ?? null;
      });

    if (editGoodsForm["showMinPrice"]) {
      editGoodsForm["showMinPrice"] = editGoodsForm["showMinPrice"] / 100;
    }

    flag.value = canEdit(editGoodsForm.detailText)
    richEditorInitialValue.value = rs.payload?.detailText ?? "";
  }
};
//替换富文本字符
const formatStr = (str) => {
  return str.replaceAll(/\\n/g, '')
}

//判断富文本是否可以编辑
const canEdit = (text) => {
  if (text && typeof text == 'string') {
    if (text.startsWith('<style>')) {
      return false
    }
    return true
  }
  return true
}

const handleDialogOpened = () => {
  getGoodsCate();

  if (props.rowData.id) {
    _getGoodsDetail();
  }
};
</script>

<style scoped lang="scss">
.line-input {
  display: flex;
  flex-wrap: nowrap;
}

.text-box {
  width: 100%;
  overflow-y: auto;
  height: 54vh;
  border: 1px solid var(--el-border-color);
}
</style>
